#include <REGX52.H>
#include "Key.h"
#include "Nixie.h"
#include "Timer0.h"
#include "AT24C02.h"
#include "Delay.h"

unsigned char isRunning = 0;
unsigned char ms, sec, min;

void main() {
	unsigned char key;
	Timer0_Init();
	
	while (1) {
		
		key = Key();
		switch (key) {
			case 1: // 开始or暂停
				isRunning = !isRunning;
			break;
			case 2:	// 清零
				ms = 0;
				sec = 0;
				min = 0;
			break;
			case 3:
				AT24C02_WriteByte(0, min);
				Delay(5);
				AT24C02_WriteByte(1, sec);
				Delay(5);
				AT24C02_WriteByte(2, ms);
				Delay(5);
			break;
			case 4:
				min = AT24C02_ReadByte(0);
				sec = AT24C02_ReadByte(1);
				ms = AT24C02_ReadByte(2);
			break;
		}
	
		Nixie_SetRefreshTable(1, min / 10);
		Nixie_SetRefreshTable(2, min % 10);
		Nixie_SetRefreshTable(3, 16);
		Nixie_SetRefreshTable(4, sec / 10);
		Nixie_SetRefreshTable(5, sec % 10);
		Nixie_SetRefreshTable(6, 16);
		Nixie_SetRefreshTable(7, ms / 10);
		Nixie_SetRefreshTable(8, ms % 10);
	}
}

void SecCalc() {
	if (isRunning) {
		ms++;
		if (ms >= 100) {
			ms = 0;
			sec++;
			if (sec >= 60) {
				sec = 0;
				min++;
				if (min >= 60) 
					min = 0;
			}
		}
	}
}

void Timer0_Isr(void) interrupt 1
{
	static unsigned char keyCounter = 0;
	static unsigned char nixieCounter = 0;
	static unsigned char secCounter = 0;
	Timer0_Reload();
	
	
	keyCounter++;
	if (keyCounter >= 20) {
		keyCounter = 0;
		Key_Scan();
	}
	nixieCounter++;
	if (nixieCounter >= 2) {
		nixieCounter = 0;
		Nixie_Refresh();
	}
	secCounter++;
	if (secCounter >= 10) {
		secCounter = 0;
		SecCalc();
	}
}